package com.wisenet.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * 操作Properties工具类
 * @author fzh
 *
 */
public class PropertiesUtil {
	// 日志
	public static Logger logger = Logger.getLogger(PropertiesUtil.class);
	
	/**
	 * 实时获取配置文件中的值
	 * @param key
	 * @param filePath
	 * @return
	 */
	public static String getCurrentPropertiesValue(String key, String filePath) {
		InputStream inputStream = null;
		Properties properties = new Properties();
		try {
			inputStream = new FileInputStream(getRealPath(filePath));
			properties.load(inputStream);
			return properties.getProperty(key);
		} catch (Exception e) {
			logger.error("操作配置文件异常: " + e.getMessage());
		} finally {
			try {
				if(inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				logger.error("关闭流异常: " + e.getMessage());
			}
		}
		return null;
	}
	
	/**
	 * 非实时动态获取
	 * @param filePath
	 * @param key
	 * @return
	 */
	public static String getValue(String filePath, String key) {
		Properties properties = getProperties(filePath);
		return properties == null ? null : properties.getProperty(key);
	}
	
	/**
	 * 设置文件
	 * @param filePath
	 * @param key
	 * @param value
	 * @return
	 */
	public static boolean setProperty(String filePath, String key, String value) {
		FileOutputStream outputStream = null;
		try {
			Properties properties = getProperties(filePath);
			if (properties == null) {
				return false;
			}
			// 设置
			properties.setProperty(key, value);
			// 写到配置文件，此处要获取真实路径
			outputStream = new FileOutputStream(getRealPath(filePath));
			properties.store(outputStream, "update properties");
			return true;
		} catch (Exception e) {
			logger.error("FileNotFoundException: " + e.getMessage());
		} finally {
			try {
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (IOException e) {
				logger.error("关闭流异常: " + e.getMessage());
			}
		}
		return false;
	}

	/**
	 * 获取配置文件真实路径
	 * @param fileName
	 * @return
	 */
	public static String getRealPath(String fileName) {
		String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		return path + File.separator + fileName;
	}
	
	/**
	 * 获取配置文件
	 * @param filePath
	 * @return
	 */
	public static Properties getProperties(String filePath) {
		InputStream inputStream = null;
		try {
			Properties properties = new Properties();
			// 加载
			properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(filePath));
			return properties;
		} catch (Exception e) {
			logger.error("加载配置文件异常: " + e.getMessage());
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				logger.error("关闭流异常: " + e.getMessage());
			}
		}
		return null;
	}
}
